<?php
namespace mirage\core;
if(!defined('MIRAGE_MODE')) die('Forbidden');
use \mirage\Mirage;
use mirage\core\SystemException;
/**
 * Description of BaseController
 * Date Created Aug 30, 2011 11:18:06 AM
 * @author Bryan Salazar
 */
class BaseController {
   public $layout = 'layouts/main';
   public $default_method = 'index';
   
   /****************************************************************************
    * Original Author: Bryan Salazar
    * Creation Date: June 1, 2011
    * Paramter: string $view (name of view)
    * Optional Paramter: array $param (variable that will pass to view)
    * Description: This method will render view with layout
    ***************************************************************************/
   public function render($view,$param=array())
   {
      $app_path = Mirage::app()->getAppPath();
      $view = $view;
      $template = $app_path . '/views/' . $view . '.php';
      if(!file_exists($template)) 
         throw new SystemException($template . ' not found');
      ob_start();
      $param = $param;
      require $template;
      $content = ob_get_contents();
      ob_end_clean();
      $layout_file = $app_path . '/views/' . $this->layout . '.php';
      
      if(!file_exists($layout_file)) 
         throw new SystemException(' layout not found '.$layout_file);
      require $layout_file;
   }

   /****************************************************************************
    * Original Author: Bryan Salazar
    * Creation Date: June 1, 2011
    * Paramter: string $view (name of view)
    * Optional Paramter: array $param (variable that will pass to view)
    * Description: This method will render view without layout
    ***************************************************************************/
   public function renderPartial($view,$param=array())
   {
      $param = $param;
      $app_path = Mirage::app()->getAppPath();
      $view = $view;
      $template = $app_path . '/views/' . $view . '.php';
      if(!file_exists($template)) 
         throw new SystemException($template . ' not found');
      
      require $template;
   }
   
   public function redirect($uri) {
      header('LOCATION: ' . $uri);
   }
   
   public function createUrl($url=array()) {
      $default_url = array(
          'controller'=>'',
          'action'=>'',
      );
      $controller = $url['controller'];
      $baseUrl = Mirage::app()->baseUrl;
     
      $url = array_merge($default_url,$url);
      
      header('LOCATION: ' . $baseUrl . '/' . $url['controller'] . $url['action']);
   }
   
   public function isAjaxRequest() {
      if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
         return true;
      return false;
   }
   
   public function isPostRequest() {
      if(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
         return true;
      return false;
   }
}
